#include <string>
#include <thread>
#include <chrono>
#include <gflags/gflags.h>
#include "../../log/log.h"

/*
[C++ 11 多线程 (2) 线程的 join 和 detach](https://zhuanlan.zhihu.com/p/608640080)
*/


void funtion(char w){
    LOG("funtion%c start", w);
    for ( int i = 0; i < 3; i++)
    {
        LOG("funtion%c %d", w, i);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    LOG("funtion%c end", w);
}

int main(int argc, char* argv[]) {
    gflags::SetUsageMessage(__DATE__ " " __TIME__ "\n多线程demo");
    gflags::SetVersionString("0.1");
    gflags::ParseCommandLineFlags(&argc, &argv, true);

    /*thread 一经构建就会开始run，并不是join/detach调用时run*/
    LOG("init threadA start.");
    std::thread threadA(funtion, 'A');
    LOG("init threadB start.");
    std::thread threadB(funtion, 'B');
    LOG("init end.\n");

    /*join 阻塞等待thread结束退出*/
    LOG("threadA.join start.");
    threadA.join();
    LOG("threadB.join start.");
    threadB.join();
    LOG("join end.\n");

    /*thread一旦调用join/detach后就会与函数解除关系，再次对thread调用join/detach会出问题*/
    // LOG("detach start.");
    // threadA.detach();
    // threadB.detach();
    // LOG("detach end.\n");
    
    /*detach 不会阻塞主线程
    那detach的存在意义是什么？
    如果thread不调用join/detach主线程退出时会出现这个"terminate called without an active exception"*/
    std::thread threadC(funtion, 'C');
    LOG("detach start.");
    threadC.detach();
    LOG("detach end.\n");

    std::this_thread::sleep_for(std::chrono::seconds(7));
    
    LOG("program end.");

    return 0;
}